<?php
$dbname="172.16.250.169/orcl";
$dbuser="libsys";
$dbpassword="libsys";
$campusapp_url="https://eaiapp.ccom.edu.cn";
$campusapp_appid="200200405134542698";
$campusapp_appsecret="smeyasjgy1tksxm9bmpv5gnhjbaf6ngu";

function _doctypecode_to_emoji($doctypecode) {
  switch($doctypecode) {
    case '01':
    case '02':
      $r='&#x1f4d7;'; break;
    case '34':
      $r='&#x1f3bc;'; break;	
    case '38':
      $r='&#x1f4bf;'; break;
    default: $r='';
  }
  return $r;
}

function _process_orcale_asciistr($str) {
        return preg_replace_callback(
                '|\\\([0-9A-F]{4})|',
                function ($matches) {
                        return mb_convert_encoding('&#'.intval('0x'.$matches[1],0).';', 'UTF-8', 'HTML-ENTITIES');
                },
                $str);
}

if($_SERVER['REQUEST_METHOD']=='GET') {
  if(!array_key_exists('code', $_GET)) $should_redirect=1;
  else {
	$url=sprintf("%s/api/third/get-token", $campusapp_url);
	$opts=['appid'=>$campusapp_appid, 'appsecret'=>$campusapp_appsecret];
	$ch = curl_init($url.'?'.http_build_query($opts));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$r=curl_exec($ch);
	$result=json_decode($r);
	if($r===FALSE || $result->e || empty($result->d->access_token)) {
		http_response_code(500);
		exit;
	}
	curl_close($ch);

	$url=sprintf("%s/uc/api/oauth/user-by-code", $campusapp_url);
	$opts=['code'=>$_GET['code'], 'access_token'=>$result->d->access_token];
	$ch = curl_init($url.'?'.http_build_query($opts));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

	$r=curl_exec($ch);
	$result=json_decode($r);
	if($r===FALSE || $result->e || empty($result->d->role->number)) {
		$should_redirect=1;
	} else {
		curl_close($ch);

		$uid=$result->d->role->number;
		$uname=$result->d->realname;
	}
  }
  
  if($should_redirect==1) {
        $url=sprintf('Location: %s/uc/api/oauth/index?redirect=%s&appid=%s',
		$campusapp_url,
		urlencode(sprintf('%s://%s%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])),
		$campusapp_appid
	);
        header($url, TRUE, 302);
        exit;
  }
}

?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <title>借阅历史</title>
    <script src="//cdn.bootcss.com/jquery/3.5.0/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/pulltorefreshjs/0.1.20/index.umd.min.js"></script>
<?php
if(preg_match('/wxwork\//', $_SERVER['HTTP_USER_AGENT'])) {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.4/weui-for-work.min.css"/>
<?php
} else {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
<?php
}
?>
</head>
<body>
<div class="page panel list">
<?php
try {
	$dbh = new PDO("oci:dbname=//".$dbname.";charset=AL32UTF8", $dbuser, $dbpassword);
	$sql_temp=
"SELECT 1 FROM DUAL ".
"WHERE EXISTS(".
"SELECT * FROM LEND_HIST INNER JOIN READER ON LEND_HIST.CERT_ID_F=READER.CERT_ID ".
"INNER JOIN READER_CERT ON READER.CERT_ID=READER_CERT.CERT_ID ".
"WHERE READER_CERT.REDR_CERT_ID='%s' AND READER.NAME='%s')";
	$sql=sprintf($sql_temp, $uid, $uname);
	$results=$dbh->query($sql)->fetchAll();
	if (count($results)>0) {
?>
	<div class="weui-panel">
	<div class="weui-panel__hd"><?php
		echo sprintf("%s (%s) ", $uname, $uid);
		if(!isset($_GET['start_year'])) echo '今年';
		elseif($_GET['start_year']=='0') echo sprintf('%s年及更早', $_GET['end_year']);
		elseif($_GET['start_year']==$_GET['end_year']) echo sprintf("%s年",$_GET['start_year']);
		else echo sprintf('%s年至%s年',$_GET['start_year'], $_GET['end_year']);
	?>的借阅历史</div>
	<div class="weui-panel__bd">
        <?php
	$sql_temp=
"SELECT ASCIISTR(MARC.M_TITLE) AS M_TITLE, ASCIISTR(MARC.M_AUTHOR) AS M_AUTHOR, LEND_HIST.PROP_NO_F AS PROP_NO, LEND_HIST.LEND_DATE, MARC.DOC_TYPE_CODE, ".
"DOC_TYPE_CODE.DOC_TYPE_NAME, INDI_ACCT.CALL_NO, ITEM.BOOK_LEND_FLAG ".
"FROM LEND_HIST INNER JOIN READER ON LEND_HIST.CERT_ID_F=READER.CERT_ID ".
"INNER JOIN READER_CERT ON READER.CERT_ID=READER_CERT.CERT_ID ".
"INNER JOIN INDI_ACCT ON LEND_HIST.PROP_NO_F=INDI_ACCT.PROP_NO ".
"INNER JOIN MARC ON INDI_ACCT.MARC_REC_NO=MARC.MARC_REC_NO ".
"INNER JOIN ITEM ON INDI_ACCT.PROP_NO=ITEM.PROP_NO ".
"INNER JOIN DOC_TYPE_CODE ON MARC.DOC_TYPE_CODE=DOC_TYPE_CODE.DOC_TYPE_CODE ".
"WHERE READER_CERT.REDR_CERT_ID='%s' AND READER.NAME='%s' AND RET_DATE IS NOT NULL ".
"AND LEND_DATE>='%s-01-0100:00:00' AND LEND_DATE<='%s-12-3123:59:59' ".
"ORDER BY LEND_DATE DESC, PROP_NO ASC";
	$sql=sprintf($sql_temp, $uid, $uname, array_key_exists('start_year', $_GET)?$_GET['start_year']:date('Y'), array_key_exists('end_year', $_GET)?$_GET['end_year']:date('Y'));
	$results=$dbh->query($sql)->fetchAll();

	$prop_nos=[];
        foreach ($results as $item) {
		if(!isset($prop_nos[$item['CALL_NO']])) $prop_nos[$item['CALL_NO']]=[];
		$prop_nos[$item['CALL_NO']]['TITLE']=preg_replace('/[ ]*\/$/', '', trim(_process_orcale_asciistr($item['M_TITLE'])));
		$prop_nos[$item['CALL_NO']]['AUTHOR']=preg_replace('/^(\/)/', '', trim(_process_orcale_asciistr($item['M_AUTHOR'])));
		$prop_nos[$item['CALL_NO']]['DOC_TYPE_NAME']=$item['DOC_TYPE_CODE'];
		if(!isset($prop_nos[$item['CALL_NO']]['LEND_DATE'])) $prop_nos[$item['CALL_NO']]['LEND_DATE']=[];
		if(count($prop_nos[$item['CALL_NO']]['LEND_DATE'])>3) {
		} elseif(count($prop_nos[$item['CALL_NO']]['LEND_DATE'])==3) {
			$prop_nos[$item['CALL_NO']]['LEND_DATE'][]='...';
		} else {
			$prop_nos[$item['CALL_NO']]['LEND_DATE'][]=substr($item['LEND_DATE'], 0, 10);
			$prop_nos[$item['CALL_NO']]['LEND_DATE']=array_unique($prop_nos[$item['CALL_NO']]['LEND_DATE']);
		}
		if(!isset($prop_nos[$item['CALL_NO']]['LEND_COPIES'])) $prop_nos[$item['CALL_NO']]['LEND_COPIES']=0;
		if($item['BOOK_LEND_FLAG']=='0')
			$prop_nos[$item['CALL_NO']]['LEND_COPIES']++;
	}

	if(count($prop_nos)==0) {
	?>
		<div class="weui-media-box weui-media-box_text">
			<h4 class="weui-media-box__title">无借书记录</h4>
		</div>
	<?php
	} else {
	foreach ($prop_nos as $call_no => $prop_no) {
        ?>
		<div class="weui-media-box weui-media-box_text">
			<h4 class="weui-media-box__title"><?php echo sprintf("%s %s / %s", _doctypecode_to_emoji($prop_no['DOC_TYPE_NAME']), $prop_no['TITLE'], $prop_no['AUTHOR']); ?></h4>
			<p class="weui-media-box__desc"><?php
				echo sprintf('<span style="vertical-align: middle">%s</span>%s <span style="vertical-align: middle">借出日期：%s</span>', $call_no,
					$prop_no['LEND_COPIES']==-1?' <span class="weui-badge" style="margin-left: 5px;">当前无可借复本</span> ':'',
					implode(', ', $prop_no['LEND_DATE'])); ?></p>
		</div>
        <?php
        }}

	$sql_temp=
"SELECT 1 FROM DUAL ".
"WHERE EXISTS(".
"SELECT * FROM LEND_HIST INNER JOIN READER ON LEND_HIST.CERT_ID_F=READER.CERT_ID ".
"INNER JOIN READER_CERT ON READER.CERT_ID=READER_CERT.CERT_ID ".
"WHERE READER_CERT.REDR_CERT_ID='%s' AND READER.NAME='%s' AND LEND_DATE<'%s-01-0100:00:00')";
	$sql=sprintf($sql_temp, $uid, $uname, array_key_exists('start_year', $_GET)?$_GET['start_year']:(array_key_exists('end_year', $_GET)?$_GET['end_year']:date('Y')));

        $results=$dbh->query($sql)->fetchAll();
        if (count($results)>0) {
	$url=sprintf('%s://%s%s?start_year=%s&end_year=%s', 
		$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['PHP_SELF'],
		array_key_exists('start_year', $_GET)?($_GET['start_year']-1):(intval(date('Y'))-1),
		array_key_exists('start_year', $_GET)?($_GET['start_year']-1):(intval(date('Y'))-1)
	);
        ?>
	</div>
	<div class="weui-panel__ft">
                <a href="<?php echo $url; ?>" class="weui-cell weui-cell_access weui-cell_link">
                    <div class="weui-cell__bd">查看<?php echo array_key_exists('start_year', $_GET)?$_GET['start_year']:(array_key_exists('end_year', $_GET)?$_GET['end_year']:date('Y'));?>年之前的借阅记录</div>
                    <span class="weui-cell__ft"></span>
                </a>
        </div>
	</div>
<?php
	};
	} else {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-info weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">无借阅历史</h2><p class="weui-msg__desc"><?php echo sprintf("%s (%s) ",$uname, $uid); ?>从未借过书。</p></div>
	</div>
	</div>
<?php
	}

} catch (PDOException $e) {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-warn weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">错误</h2><p class="weui-msg__desc"><?php echo sprintf("%s: %s",$e->getCode(), $e->getMessage()); ?></p></div>
	</div>
	</div>
<?php
} finally {
	$dbh=null;
}
?>
</div>
<script type="text/javascript">
$(function(){
	const ptr = PullToRefresh.init({
		instructionsPullToRefresh: '下拉可刷新',
		instructionsReleaseToRefresh: '松开可刷新',
		instructionsRefreshing: '刷新中',
		onRefresh() {
			window.location.href='<?php
				$query=[];
				if(array_key_exists('start_year', $_GET)) $query['start_year']=$_GET['start_year'];
				if(array_key_exists('end_year', $_GET)) $query['end_year']=$_GET['end_year'];
				$opts=http_build_query($query);
				echo sprintf('%s://%s%s%s%s',
					$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['PHP_SELF'],
					empty($opts)?'':'?', $opts);
?>';
		}
	});
});
</script>
</body>
</html>
